/* 
 * File:   main.c
 *
 * Created on February 9, 2010, 10:53 AM
 */

#include <stdio.h>
#include <stdlib.h>
#include <p33Fxxxx.h>

_FOSCSEL(FNOSC_PRIPLL);
_FOSC(FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMD_XT);
_FWDT(FWDTEN_OFF);

/*
 * 
 */
void delay(void) {
    long i = 524280;
    while(i--)
        ;
}


void __attribute__((__interrupt__)) _T2Interrupt( void )
{
/* Interrupt Service Routine code goes here */
//OC1RS = 300; // Write Duty Cycle value for next PWM cycle
IFS0bits.T2IF = 0; // Clear Timer 2 interrupt flag
}

void init(void)
{
    // Initialize Output Compare Module
OC1CONbits.OCM = 0b000; // Disable Output Compare Module
OC1R = 100; // Write the duty cycle for the first PWM pulse
OC1RS = 4688; // Write the duty cycle for the second PWM pulse      //3125 = 1 ms
OC1CONbits.OCTSEL = 0; // Select Timer 2 as output compare time base
OC1R = 100; // Load the Compare Register Value
OC1CONbits.OCM = 0b110; // Select the Output Compare mode
// Initialize and enable Timer2
T2CONbits.TON = 0; // Disable Timer
T2CONbits.TCS = 0; // Select internal instruction cycle clock
T2CONbits.TGATE = 0; // Disable Gated Timer mode
T2CONbits.TCKPS = 0b01; // Select 1:8 Prescaler
TMR2 = 0x00; // Clear timer register
PR2 = 31250; // Load the period value
IPC1bits.T2IP = 0x01; // Set Timer 2 Interrupt Priority Level
IFS0bits.T2IF = 0; // Clear Timer 2 Interrupt Flag
IEC0bits.T2IE = 0; // Enable Timer 2 interrupt
T2CONbits.TON = 1; // Start Timer
/* Example code for Timer 2 ISR*/

}

int main(void){ //int argc, char** argv) {
    init();

    while(1)
    {

    }
//
//    int counter;
//
//    /* set LEDs (D3-D10/RA0-RA7) drive state low */
//    LATA = 0xFF00;
//    /* set LED pins (D3-D10/RA0-RA7) as outputs */
//    TRISA = 0xFF00;
//    int j = 1;
//    int dir = 0;
//    while(1) {
//        if (dir == 0){
//            if (j < 0xFF){
//                j = j*2;
//            }
//            else
//            {
//                dir = 1;
//            }
//        }
//        if (dir == 1){
//            if (j > 1){
//                j = j/2;
//            }
//            else
//            {
//                dir = 0;
//            }
//        }
//        LATA = j;
//        delay();
//        LATA = 0;
//        delay();
//    }
    return (EXIT_SUCCESS);
}
